﻿using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class FtPictFmla: ObjItem
    {
        private ushort _cb;
        private uint? _cbBufInCtlStm;
        private ObjFmla _fmla;
        private PictFmlaKey _key;
        private uint? _lPosInCtlStm;

        protected override void WriteContent(BinaryWriter writer)
        {
            long cbPosition = writer.BaseStream.Position;
            writer.Write(_cb);
            if (_fmla != null)
            {
                _fmla.Write(writer);
                if (_lPosInCtlStm != null)
                {
                    writer.Write(_lPosInCtlStm.Value);
                    if (_cbBufInCtlStm != null)
                    {
                        writer.Write(_cbBufInCtlStm.Value);
                        if (_key != null)
                        {
                            _key.Write(writer);
                        }
                    }
                }
            }
            long newPosition = writer.BaseStream.Position;
            writer.BaseStream.Position = cbPosition;
            writer.Write((ushort)(newPosition - cbPosition - 2));
            writer.BaseStream.Position = newPosition;
        }

        protected override void ReadContent(BinaryReader reader)
        {
            _cb = reader.ReadUInt16();
            long position = reader.BaseStream.Position;
            _fmla = new ObjFmla();
            _fmla.Read(reader, true);
            if (reader.BaseStream.Position - position == _cb)
                return;
            _lPosInCtlStm = reader.ReadUInt32();
            if (reader.BaseStream.Position - position == _cb)
                return;
            _cbBufInCtlStm = reader.ReadUInt32();
            if (reader.BaseStream.Position - position == _cb)
                return;
            _key = new PictFmlaKey();
            _key.Read(reader);
        }

        protected override FtType Ft
        {
            get { return FtType.FtPictFmla; }
        }
    }
}